package search

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"wechat/global"
	"wechat/handle/request"
	"wechat/pkg"
)

// 短信
func Sms(c *gin.Context) {
	var form request.Sms
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	sms := rand.Intn(900000) + 100000
	sendSms, err := pkg.SendSms(form.Phone, strconv.Itoa(sms))
	if err != nil {
		return
	}

	send, _ := global.Rdb.Get(global.Ctx, "SendSms_"+form.Phone).Int()
	if send >= 3 {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "同一手机号1分钟内最多发送3条验证码",
		})
		return
	}

	if sendSms.Code != 2 {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "短信发送失败",
		})
		return
	}

	global.Rdb.Set(global.Ctx, "sendSms_"+form.Phone, sms, time.Minute*30)
	global.Rdb.Incr(global.Ctx, "SendSms_"+form.Phone)
	global.Rdb.Expire(global.Ctx, "SendSms_"+form.Phone, time.Minute*1)

	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "验证码发送成功",
	})

}
